<template>
  <div class="game-board" id="gameBoard">
    <div v-for="(row, rowIndex) in gameStore.games.board" :key="rowIndex" class="row">
      <div v-for="(card, colIndex) in row" :key="`${rowIndex}-${colIndex}`" class="card-container">
        <CardComponent 
          v-if="card" 
          :key="`${rowIndex}-${colIndex}-${card.suit}-${card.specialType}`" 
          :card="card"
          @click="handleCardClick(card.row, card.col)" 
        />
        <div v-if="card && card.isMatched" class="remove-animation"></div>
      </div>
    </div>
    
    <!-- 特效元素 -->
    <div v-for="(effect, index) in effects" :key="'effect-'+index" 
         :class="['special-effect', effect.type + '-effect']"
         :style="{
           top: effectStyle(effect).top,
           left: effectStyle(effect).left,
           width: effectStyle(effect).width,
           height: effectStyle(effect).height
         }">
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import CardComponent from '@/components/Card.vue'
import { useGameStore } from '@/store/game'

const gameStore = useGameStore();
const effects = ref([]);

// 计算卡片大小和间距
const cardSize = computed(() => {
  return (500 - 30 - 4 * 7) / 8; // (width - padding - gaps) / count
});

const effectStyle = (effect) => {
  const size = cardSize.value;
  const gap = 4;
  const padding = 15;
  
  switch(effect.type) {
    case 'horizontal':
      return {
        top: `${padding + effect.row * (size + gap)}px`,
        left: `${padding}px`,
        width: `${500 - padding * 2}px`,
        height: `${size}px`
      };
    case 'vertical':
      return {
        top: `${padding}px`,
        left: `${padding + effect.col * (size + gap)}px`,
        width: `${size}px`,
        height: `${500 - padding * 2}px`
      };
    case 'joker':
    case 'bomb':
      return {
        top: `${padding + effect.row * (size + gap)}px`,
        left: `${padding + effect.col * (size + gap)}px`,
        width: `${size}px`,
        height: `${size}px`
      };
    default:
      return {};
  }
};

// 添加防卡死计时器
let safetyTimeout = null;
const SAFETY_TIMEOUT_MS = 3000; // 减少到3秒安全超时

// 加快游戏速度的延迟常量
const DELAY_HIGHLIGHT = 100;    // 高亮延迟从200ms减少到100ms
const DELAY_CARD_CHANGE = 80;   // 卡片变化延迟从150ms减少到80ms
const DELAY_EFFECT = 250;       // 特效延迟从400ms减少到250ms
const DELAY_REMOVE = 100;       // 移除延迟从200ms减少到100ms
const DELAY_DROP = 100;         // 下落延迟从200ms减少到100ms
const DELAY_REFILL = 100;       // 补充延迟从200ms减少到100ms
const DELAY_SPECIAL_CREATE = 50; // 特殊卡片创建延迟从100ms减少到50ms

const handleCardClick = async (row, col) => {
  if (gameStore.games.isProcessing) return;
  
  // 设置安全超时，防止处理过程卡死
  safetyTimeout = setTimeout(() => {
    if (gameStore.games.isProcessing) {
      console.warn("处理超时，强制重置游戏状态");
      gameStore.games.isProcessing = false;
      gameStore.resetEffectChainDepth();
      clearTimeout(safetyTimeout);
    }
  }, SAFETY_TIMEOUT_MS);
  
  gameStore.games.isProcessing = true;
  
  try {
    // 获取点击的卡片
    const clickedCard = gameStore.games.board[row][col];
    
    // 如果点击的是特殊卡片，触发特殊效果
    if (clickedCard.specialType !== 'none') {
      // 获取所有相邻的特殊卡片和当前点击的特殊卡片
      const specialCardsToTrigger = gameStore.findAdjacentSpecialCards(row, col);
      specialCardsToTrigger.push({
        row, 
        col, 
        type: clickedCard.specialType, 
        suit: clickedCard.suit
      });
      
      await triggerMultipleSpecialEffects(specialCardsToTrigger);
      clearTimeout(safetyTimeout);
      return;
    }
    
    // 普通卡片点击逻辑
    const cardsToChange = [[row, col]]; // 自身
    
    // 上
    if (row > 0) cardsToChange.push([row - 1, col]);
    // 下
    if (row < gameStore.games.size - 1) cardsToChange.push([row + 1, col]);
    // 左
    if (col > 0) cardsToChange.push([row, col - 1]);
    // 右
    if (col < gameStore.games.size - 1) cardsToChange.push([row, col + 1]);
    
    // 先高亮显示所有将被影响的卡片
    cardsToChange.forEach(([r, c]) => {
      if (gameStore.games.board[r][c]) {
        gameStore.games.board[r][c].isHighlighted = true;
      }
    });
    
    await delay(DELAY_HIGHLIGHT);
    
    // 移除高亮并执行变化动画
    let processedCards = 0;
    const totalCards = cardsToChange.length;
    
    cardsToChange.forEach(([r, c], index) => {
      if (gameStore.games.board[r][c]) {
        gameStore.games.board[r][c].isHighlighted = false;
        gameStore.games.board[r][c].isChanging = true;
        
        setTimeout(() => {
          gameStore.toggleCardSuit(r, c);
          
          processedCards++;
          if (processedCards === totalCards) {
            checkMatches().finally(() => {
              clearTimeout(safetyTimeout);
            });
          }
        }, DELAY_CARD_CHANGE + index * 20); // 减少间隔时间
      }
    });
  } catch (error) {
    console.error("处理卡片点击时出错:", error);
    gameStore.games.isProcessing = false;
    gameStore.resetEffectChainDepth();
    clearTimeout(safetyTimeout);
  }
};

const triggerMultipleSpecialEffects = async (specialCards) => {
  gameStore.incrementEffectChainDepth();
  
  if (gameStore.games.effectChainDepth > gameStore.MAX_CHAIN_DEPTH) {
    console.warn("特效连锁深度超过限制，终止连锁");
    gameStore.games.isProcessing = false;
    gameStore.resetEffectChainDepth();
    return;
  }
  
  const allMatchedPositions = new Set();
  let totalScore = 0;
  
  // 记录已经被触发的特效卡片位置，避免重复触发
  const triggeredCards = new Set();
  specialCards.forEach(card => {
    triggeredCards.add(`${card.row},${card.col}`);
  });
  
  // 处理所有特效 - 添加防卡死机制
  try {
    for (const effect of specialCards) {
      const effectKey = `${effect.row},${effect.col}`;
      
      // 创建特效动画
      createEffectAnimation(effect);
      
      // 获取影响范围
      const positions = gameStore.getEffectRange(effect);
      positions.forEach(pos => allMatchedPositions.add(pos));
      totalScore += positions.size * 8;
      
      await delay(DELAY_EFFECT);
    }
  } catch (error) {
    console.error("特效处理出错:", error);
    gameStore.games.isProcessing = false;
    gameStore.resetEffectChainDepth();
    return;
  }
  
  // 更新分数
  gameStore.games.score += totalScore;
  
  // 移除所有匹配卡片并获取需要触发的特殊卡片
  const specialCardsToTrigger = gameStore.removeCards(allMatchedPositions);
  
  // 关键修改：过滤掉已经被触发的特效卡片，避免重复触发
  const filteredSpecialCards = specialCardsToTrigger.filter(card => 
    !triggeredCards.has(`${card.row},${card.col}`)
  );
  
  await delay(DELAY_REMOVE);
  
  // 卡片下落和补充
  gameStore.dropCards();
  await delay(DELAY_DROP);
  
  gameStore.refillBoard();
  await delay(DELAY_REFILL);
  
  // 如果有特殊卡片被触发，继续连锁
  if (filteredSpecialCards.length > 0) {
    await triggerMultipleSpecialEffects(filteredSpecialCards);
  } else {
    // 重置连锁深度并再次检查匹配
    gameStore.resetEffectChainDepth();
    checkMatches();
  }
};

const createEffectAnimation = (effect) => {
  effects.value.push({
    id: Date.now() + Math.random(),
    type: effect.type,
    row: effect.row,
    col: effect.col
  });
  
  setTimeout(() => {
    effects.value = effects.value.filter(e => e.id !== effect.id);
  }, DELAY_EFFECT + 200); // 保持与特效延迟一致
};

const checkMatches = async () => {
  const result = gameStore.checkMatches();
  
  if (result.hasMatches) {
    gameStore.games.comboCount++;
    
    // 限制连击次数，防止无限循环
    if (gameStore.games.comboCount > gameStore.MAX_COMBO_COUNT) {
      console.warn("连击次数过多，强制终止");
      gameStore.games.isProcessing = false;
      gameStore.games.comboCount = 0;
      return;
    }
    
    // 先生成特殊卡片
    if (result.specialCardsToCreate.length > 0) {
      gameStore.createSpecialCards(result.specialCardsToCreate);
      await delay(DELAY_SPECIAL_CREATE);
    }
    
    // 移除匹配的卡片并获取需要触发的特殊卡片
    const specialCardsToTrigger = gameStore.removeCards(result.matchedPositions);
    await delay(DELAY_REMOVE);
    
    // 关键修改：如果有特殊卡片被触发，先触发这些特效
    if (specialCardsToTrigger.length > 0) {
      await triggerMultipleSpecialEffects(specialCardsToTrigger);
    } else {
      // 卡片下落和补充
      gameStore.dropCards();
      await delay(DELAY_DROP);
      
      gameStore.refillBoard();
      await delay(DELAY_REFILL);
      
      // 递归检查匹配
      checkMatches();
    }
  } else {
    gameStore.games.isProcessing = false;
    gameStore.games.comboCount = 0;
  }
};

const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
</script>

<style scoped>
.game-board {
  width: 500px;
  height: 500px;
  background: rgba(0, 0, 0, 0.25);
  border-radius: 12px;
  padding: 15px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
  display: grid;
  grid-template-columns: repeat(8, 1fr);
  grid-gap: 4px;
  position: relative;
  margin: 0 auto;
}

.row {
  display: contents;
}

.card-container {
  position: relative;
  width: 100%;
  height: 100%;
}

.remove-animation {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(255, 255, 255, 0.7);
  border-radius: 6px;
  animation: remove 0.2s forwards; /* 加快移除动画 */
}

@keyframes remove {
  0% { transform: scale(1); opacity: 1; }
  100% { transform: scale(0); opacity: 0; }
}

.special-effect {
  position: absolute;
  pointer-events: none;
  z-index: 100;
}

.horizontal-effect {
  width: 100%;
  height: 8px;
  background: linear-gradient(90deg, transparent, cyan, transparent);
  animation: horizontalBeam 0.3s forwards; /* 加快特效动画 */
}

@keyframes horizontalBeam {
  0% { width: 0; opacity: 0; }
  50% { width: 100%; opacity: 1; }
  100% { width: 100%; opacity: 0; }
}

.vertical-effect {
  width: 8px;
  height: 100%;
  background: linear-gradient(0deg, transparent, lime, transparent);
  animation: verticalBeam 0.3s forwards; /* 加快特效动画 */
}

@keyframes verticalBeam {
  0% { height: 0; opacity: 0; }
  50% { height: 100%; opacity: 1; }
  100% { height: 100%; opacity: 0; }
}

.bomb-effect {
  width: 25px;
  height: 25px;
  border-radius: 50%;
  background: radial-gradient(circle, orange, red);
  animation: bombExplosion 0.3s forwards; /* 加快特效动画 */
  transform: translate(-50%, -50%);
  top: 50%;
  left: 50%;
}

@keyframes bombExplosion {
  0% { transform: translate(-50%, -50%) scale(0); opacity: 0; }
  50% { transform: translate(-50%, -50%) scale(2.5); opacity: 1; }
  100% { transform: translate(-50%, -50%) scale(4); opacity: 0; }
}

.joker-effect {
  width: 100%;
  height: 100%;
  background: radial-gradient(circle, rgba(255,0,255,0.4), transparent);
  animation: jokerPulse 0.4s forwards; /* 加快特效动画 */
  border-radius: 6px;
}

@keyframes jokerPulse {
  0% { transform: scale(0); opacity: 0; }
  50% { transform: scale(1.1); opacity: 0.6; }
  100% { transform: scale(1.4); opacity: 0; }
}
</style>